﻿using AllInOne.Classes;
using AllInOne.HDI.CRT_591_M001;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace AllInOne.MainPages
{
    /// <summary>
    /// Auth.xaml 的交互逻辑
    /// </summary>
    public partial class ReadCard : Window
    {
        /// <summary>
        /// 设置可以进卡、读取卡号
        /// </summary>
        internal int AuthType;
        internal string AuthCode;
        private UInt32 Hdle = 0;

        //AuthViewModel viewModel = new AuthViewModel() { IDCardMsg = "身份证读卡器未连接！", CountDown = Classes.SystemParam.CountDownAuth };
        AuthViewModel viewModel = new AuthViewModel() { IDCardMsg = "", CountDown = Classes.SystemParam.CountDownReadCard };
        public ReadCard(UInt32 _Hdle)
        {
            InitializeComponent();
            TbAuthCode.Focus();
            DataContext = viewModel;
            Hdle = _Hdle;
        }

        readonly CancellationTokenSource tokenSource = new CancellationTokenSource();
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            AuthCode = "";
            Cpb.Maximum = viewModel.CountDown;
            //先将发卡机的可进卡给打开
            string msg = "";
            if (!GrantCardClient.AllCardIn(Hdle, "00", out msg))
            {
                //AppendText("允许进卡失败：" + msg);
                //txtbShowTip.Text = "允许进卡失败：" + msg;
                MessageBox.Show("允许进卡失败：" + msg);
                return;
            }
            
            CancellationToken token = tokenSource.Token;
            //提示弹框
            Task countTask = new Task(() =>
            {
                while (true)
                {
                    if (!token.IsCancellationRequested)
                    {
                        viewModel.CountDown--;
                        if (viewModel.CountDown == 0)
                            QuitView(false);
                        Thread.Sleep(1000);
                    }
                    else
                        return;
                }
            }, token);
            countTask.Start();

            //读取IC卡--卡号信息
            Task task = new Task(async () =>
            {
                while (true)
                {
                    if (token.IsCancellationRequested)
                        return;
                    var result = ReadData();
                    if (!string.IsNullOrEmpty(result))
                    {
                        //进卡口关闭
                        try
                        {
                            if (!GrantCardClient.NoCardIn(Hdle, "00", out msg))
                            {
                                Log.Info($"进卡口关闭失败！");
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Info($"进卡口关闭出错：" + ex.ToString());
                        }
                        //读取到卡号
                        AuthCode = result;
                        QuitView(true);
                    }
                    await Task.Delay(500);
                }
            }, token);
            task.Start();

            //放卡--提示语音
            Task taskTip = new Task(() =>
            {
                VoiceHelper.Speak("请将IC卡推入卡槽");
            }, token);
            taskTip.Start();
        }

        private void QuitView(bool result)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                tokenSource.Cancel();
                this.DialogResult = result;
                this.Close();
            }));
        }


        private void ReadIDCard()
        {
            try
            {
                //截断数据获得证件类型标识
                //模拟读取数据--20秒
                Thread.Sleep(20000);
                AuthCode = "CardNum130911049";
                Log.Info($"身份证号：{AuthCode}");
                QuitView(true);
            }
            catch (Exception ex)
            {
                Log.Error(nameof(ReadIDCard), ex);
            }
        }





        public string ReadData()
        {
            string UID = "";
            string msg = "";
            try
            {
                //先激活
                if (!GrantCardClient.MiCardActivate(Hdle, "00", out UID, out msg))
                {
                    return "";
                }
                //下电释放--下电
                if (GrantCardClient.MiCardDactivate(Hdle, "00", out msg))
                {
                    return UID;//返回卡号
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }


        private void BdQuit_Click(object sender, RoutedEventArgs e)
        {
            QuitView(false);
        }

        private void TbAuthCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && TbAuthCode.Text.Length > 0)
            {
                AuthType = 0;
                AuthCode = TbAuthCode.Text;
                TbAuthCode.Text = "";
                Log.Info($"二维码：{AuthCode}");
                QuitView(true);
            }
        }
    }
}
